﻿using eSSP_example.Database;
using eSSP_example.Entity;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//using System.Web.UI.WebControls;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;

namespace eSSP_example.Services
{
    public class DbHelperService
    {
        private static DbHelperService instance = null;

        private static string STORAGE_FILE = "dbConfig.json";

        private List<TokenSet> tokenSetList = new List<TokenSet>();

        /// <summary>
        ///     
        /// </summary>
        private DbHelperService()
        {
            //  Load Configuration
            loadConfiguration();
        }

        /// <summary>
        ///     getInstance
        /// </summary>
        /// <returns></returns>
        public static DbHelperService getInstance()
        {
            if  (instance == null)
            {
                instance = new DbHelperService();
            }

            return  instance;
        }

        /// <summary>
        ///     loadConfiguration
        /// </summary>
        public void loadConfiguration()
        {
            //  Read config.ini file
            string jsonFilePath = Path.Combine(Directory.GetCurrentDirectory(), STORAGE_FILE);

            if  (!File.Exists(jsonFilePath))
            {
                initEmptyTokenSetFile(jsonFilePath);
            }

            string json = File.ReadAllText(jsonFilePath);

            tokenSetList = JsonConvert.DeserializeObject<List<TokenSet>>(json);
        }

        /// <summary>
        ///     initEmptyTokenStoreFile
        /// </summary>
        /// <param name="jsonFile"></param>
        private void initEmptyTokenSetFile(String jsonFile)
        {
            //  make an empty list
            List<TokenSet> tokenSetLists = new List<TokenSet>();
            tokenSetLists.Clear();

            string json = JsonConvert.SerializeObject(tokenSetLists);

            File.WriteAllText(jsonFile, json);
        }

        /// <summary>
        ///     insertToken
        /// </summary>
        /// <param name="token"></param>
        /// <param name="username"></param>
        /// <param name="expire_time"></param>
        /// <returns></returns>
        public bool insertToken(String token, String username, long expire_time)
        {
            string jsonFilePath = Path.Combine(Directory.GetCurrentDirectory(), STORAGE_FILE);

            if  (!File.Exists(jsonFilePath))
            {
                initEmptyTokenSetFile(jsonFilePath);
            }

            TokenSet tokenSet = new TokenSet();
            tokenSet.token = token;
            tokenSet.name  = username;
            tokenSet.expires_in = expire_time;

            tokenSetList.Add(tokenSet);

            string json = JsonConvert.SerializeObject(tokenSetList);

            File.WriteAllText(jsonFilePath, json);

            return  true;
        }

        /// <summary>
        ///     saveTokenlist
        /// </summary>
        /// <returns></returns>
        public int saveTokenlist()
        {
            string jsonFilePath = Path.Combine(Directory.GetCurrentDirectory(), STORAGE_FILE);

            string json = JsonConvert.SerializeObject(tokenSetList);

            File.WriteAllText(jsonFilePath, json);

            return  0;
        }

        /// <summary>
        ///     cleanApiToken
        /// </summary>
        /// <returns></returns>
        public int cleanApiToken()
        {
            string jsonFilePath = Path.Combine(Directory.GetCurrentDirectory(), STORAGE_FILE);

            initEmptyTokenSetFile(jsonFilePath);

            return  0;
        }

        /// <summary>
        ///     deleteToken
        /// </summary>    
        /// <param name="token_data"></param>
        /// <returns></returns>
        public int deleteToken(String token_data)
        {
            bool bfound = false;

            foreach (TokenSet tokenSet in tokenSetList)
            {
                if  (tokenSet.token == token_data)
                {
                    tokenSetList.Remove(tokenSet);
                    bfound = true;
                    break;
                }
            }

            if  (bfound)
            {
                //  Save Token List
                saveTokenlist();
            }

            return  1;
        }

        /// <summary>
        ///     getTokenData
        /// </summary>
        /// <param name="token_data"></param>
        /// <returns></returns>
        public TokenResponse getTokenData(String token_data)
        {
            TokenResponse rsp = null;

            foreach(TokenSet tokenSet in tokenSetList)
            {
                if  (tokenSet.token == token_data)
                {
                    rsp = new TokenResponse();

                    rsp.userName        =   tokenSet.name;
                    rsp.expires_in      =   tokenSet.expires_in;
                    rsp.access_token    =   token_data;
                    rsp.token_type      =   "bearer";
                }
            }

            return  rsp;
        }
    }
}
